#!/bin/bash -e

WORK_PATH=$(cd "$(dirname "$0")";pwd)

ANDROID_TARGET_API=$1
ANDROID_TARGET_ABI=$2
OPENSSL_VERSION=$3
ANDROID_NDK_VERSION=$4
ANDROID_NDK_PATH=${WORK_PATH}/android-ndk-${ANDROID_NDK_VERSION}
OPENSSL_PATH=${WORK_PATH}/openssl-${OPENSSL_VERSION}
OUTPUT_PATH=${WORK_PATH}/openssl_${OPENSSL_VERSION}_${ANDROID_TARGET_ABI}

if [ "$(uname -s)" == "Darwin" ]; then
    echo "Build on macOS..."
    PLATFORM="darwin"
    export alias nproc="sysctl -n hw.logicalcpu"
else
    echo "Build on Linux..."
    PLATFORM="linux"
fi

function build(){
    mkdir ${OUTPUT_PATH}

    cd ${OPENSSL_PATH}

    export ANDROID_NDK_ROOT=${ANDROID_NDK_PATH}
    export PATH=${ANDROID_NDK_ROOT}/toolchains/llvm/prebuilt/${PLATFORM}-x86_64/bin:$PATH
    export CXXFLAGS="-fPIC -Os -O2"
    export CPPFLAGS="-DANDROID -fPIC -Os -O2"
    export LDFLAGS="-Wl,-z,max-page-size=16384"

    # Cấu hình với tùy chọn `shared` thay vì `-static`
    if   [ "${ANDROID_TARGET_ABI}" == "armeabi-v7a" ]; then
        ./Configure android-arm     -D__ANDROID_API__=${ANDROID_TARGET_API} shared --prefix=${OUTPUT_PATH}
    elif [ "${ANDROID_TARGET_ABI}" == "arm64-v8a"   ]; then
        ./Configure android-arm64   -D__ANDROID_API__=${ANDROID_TARGET_API} shared --prefix=${OUTPUT_PATH}
    elif [ "${ANDROID_TARGET_ABI}" == "x86"         ]; then
        ./Configure android-x86     -D__ANDROID_API__=${ANDROID_TARGET_API} shared --prefix=${OUTPUT_PATH}
    elif [ "${ANDROID_TARGET_ABI}" == "x86_64"      ]; then
        ./Configure android-x86_64  -D__ANDROID_API__=${ANDROID_TARGET_API} shared --prefix=${OUTPUT_PATH}
    elif [ "${ANDROID_TARGET_ABI}" == "riscv64"     ]; then
        ./Configure android-riscv64 -D__ANDROID_API__=${ANDROID_TARGET_API} shared --prefix=${OUTPUT_PATH}
    else
        echo "Unsupported target ABI: ${ANDROID_TARGET_ABI}"
        exit 1
    fi

    make -j$(nproc)
    make install

    echo "Build completed! Check output libraries in ${OUTPUT_PATH}"
}

function clean(){
    if [ -d ${OUTPUT_PATH} ]; then
        rm -rf ${OUTPUT_PATH}/bin
        rm -rf ${OUTPUT_PATH}/share
        rm -rf ${OUTPUT_PATH}/ssl
        rm -rf ${OUTPUT_PATH}/lib/cmake
        rm -rf ${OUTPUT_PATH}/lib/engines-3
        rm -rf ${OUTPUT_PATH}/lib/ossl-modules
        rm -rf ${OUTPUT_PATH}/lib/pkgconfig
    fi
}

build
clean
